import Vue from 'vue';
import confirm from './Confirm.vue';

const ConfirmConstructor = Vue.extend(confirm);

const Confirm = function(options) {
  const defaultOptions = {
    title: '提示',
    message: '确定要取消该订单?',
    show: true,
  };
  return new Promise((resolve, reject) => {
    const instance = new ConfirmConstructor({
      el: document.createElement('div'),
    });
    document.body.appendChild(instance.$el);
    instance.options = {
      ...defaultOptions,
      ...options,
    };

    instance.confirm = function() {
      instance.handleAction();

      if (!instance.options.beforeClose) {
        resolve('confirm');
      } else {
        // eslint-disable-next-line accessor-pairs
        Object.defineProperty(instance.options, 'show', { // 监听实例的show属性变化
          set(val) {
            if (!val) {
              resolve('confirm');
              instance.isShow = false;
            }
          },
        });
        // 此处有一bug, 点击确定后再按esc或关闭按钮 退出确认框, 因为监听show变为false时resolve了, 所以也会执行.then中的代码
      }
    };

    instance.cancel = function() {
      reject('cancel');
      instance.isShow = false;
    };

    instance.close = function() {
      reject('close');
      instance.isShow = false;
    };
  });
};
export default Confirm;
